<?php 
/**
 * @version        $Id$
 * @author         master@xuewl.com
 * @copyright      Copyright (c) 2007 - 2014, Chongqing xuewl Information Technology Co., Ltd.
 * @link           http://www.xuewl.com
**/
namespace Admin\Controller;
class DatabaseController extends InitController
{
	public function _initialize() {
		parent::_initialize();
		$this->db = M();
		$this->version = getDbVersion();
	}

	/* 数据库备份 */
	public function export(){
		if (submitcheck('dosubmit', 'GP')) {
			$param = I('param.');			
			$tables = I('tables');
			$sqlcharset = I('sqlcharset');
			$sqlcompat = I('sqlcompat');
			$sizelimit = I('sizelimit');
			$fileid = I('fileid');
			$random = I('random');
			$tableid = I('tableid');
			$startfrom = I('startfrom');
			$tabletype = I('tabletype');
			$this->pdo_name = C('DB_NAME');
			$this->export_database($tables,$sqlcompat,$sqlcharset,$sizelimit,$action,$fileid,$random,$tableid,$startfrom,$tabletype);	
		} else {
			$db = M();
			$tbl_show = $db->query("SHOW TABLE STATUS FROM `".C('DB_NAME')."`");
			$infos = $this->status($tbl_show, C('DB_PREFIX'));
			include $this->admin_tpl('database_export');
		}
	}

	/* 数据库恢复 */
	public function import() {
		if (submitcheck('dosubmit', 'GP')) {
			$pdoname = I('pdoname');
			$this->pdoname = (empty($pdoname)) ? C('DB_NAME') : $pdoname;
			$pre = I('pre');
			$this->fileid = I('fileid');
			$this->db_charset = C('DB_CHARSET');
			$this->db_tablepre = C('DB_PREFIX');
			$this->import_database($pre);
		} else {
			$form = new \Common\Library\form();
			$pdoname = C('DB_NAME');
			$sqlfiles = glob(DATA_PATH.'bakup/'.$pdoname.'/*.sql');
			if(is_array($sqlfiles)) {
				asort($sqlfiles);
				$prepre = '';
				$info = $infos = $other = $others = array();
				foreach($sqlfiles as $id=>$sqlfile) {
					//老的数据库备份文件转换为新格式
					if(preg_match("/([phpcmstables_|db_][0-9]{8}_[0-9a-z]{20}_)([0-9]+)\.sql/i",basename($sqlfile),$num)) {
						list($tem_pre, $temp_date, $temp_string, $temp_end) = explode('_', basename($sqlfile));
						rename($sqlfile, CACHE_PATH.'bakup/'.$pdoname.'/'.$temp_string.'_'.$tem_pre.'_'.$temp_date.'_'.$temp_end);
					}
					if(preg_match("/([0-9a-z]{20}_[phpcmstables_|db_]+[0-9]{8}_)([0-9]+)\.sql/i",basename($sqlfile),$num)) {

						$info['filename'] = basename($sqlfile);
						$info['filesize'] = sizecount(filesize($sqlfile));
						$info['maketime'] = date('Y-m-d H:i:s', filemtime($sqlfile));
						$info['pre'] = $num[1];
						$info['number'] = $num[2];
						if(!$id) $prebgcolor = '#CFEFFF';
						if($info['pre'] == $prepre) {
						 $info['bgcolor'] = $prebgcolor;
						} else {
						 $info['bgcolor'] = $prebgcolor == '#CFEFFF' ? '#F1F3F5' : '#CFEFFF';
						}
						$prebgcolor = $info['bgcolor'];
						$prepre = $info['pre'];
						$infos[] = $info;
					} else {
						$other['filename'] = basename($sqlfile);
						$other['filesize'] = sizecount(filesize($sqlfile));
						$other['maketime'] = date('Y-m-d H:i:s',filemtime($sqlfile));
						$others[] = $other;
					}
				}
			}
			$show_validator = true;
			include $this->admin_tpl('database_import');
		}
	}

	public function delete() {
		$filenames = (array) I('filenames');
		$pdo_name = I('pdoname');
		$bakfile_path = DATA_PATH.'bakup'.DIRECTORY_SEPARATOR.$pdo_name.DIRECTORY_SEPARATOR;
		if (submitcheck('dosubmit')) {
			if (empty($filenames)) 
				$this->error('请选择数据库备份文件');
			foreach ($filenames as $filename) {
				if(fileext($filename) !='sql') continue;
				@unlink($bakfile_path.$filename);
			}
			$this->success('操作成功', U('import'));
		} else {
			$this->error('请勿非法访问');
		}
	}

	/**
	 * 备份文件下载
	 */
	public function public_down() {	
		$datadir = I('pdoname');
		$filename = I('filename');
		$fileext = fileext($filename);
		if($fileext != 'sql') {
			$this->error('只能下载sql文件');
		}
		file_down(DATA_PATH.'bakup'.DIRECTORY_SEPARATOR.$datadir.DIRECTORY_SEPARATOR.$filename);
	}

	/* 数据库优化&修复 */
	public function public_repair($operation = 'optimize') {
		$tables = I('tables');
		if (empty($tables)) 
			$this->error('请选择数据表');
		switch ($operation) {
			/* 数据库优化 */
			case 'optimize';				
			case 'repair';
				$tables = (array) $tables;
				foreach ($tables as $table) {
					M()->query("$operation TABLE $table");
				}
				$this->success('操作成功');
				break;
			/* 数据库结构 */
			case 'showcreat':
				$r = M()->query("SHOW CREATE TABLE $tables");
				$structure = $r[0]['Create Table'];
				$show_header = false;
				include $this->admin_tpl('database_structure');	
				break;
			default:
				# code...
				break;
		}
	}


	/**
	 * 获取数据表
	 * @param unknown_type 数据表数组
	 * @param unknown_type 表前缀
	 */
	private function status($tables,$tablepre) {
		$tpcms = array();
		$other = array();
		foreach($tables as $table) {
			$name = $table['Name'];
			$row = array('name'=>$name,'rows'=>$table['Rows'],'size'=>$table['Data_length']+$row['Index_length'],'engine'=>$table['Engine'],'data_free'=>$table['Data_free'],'collation'=>$table['Collation']);
			if(strpos($name, $tablepre) === 0) {
				$tpcms[] = $row;
			} else {
				$other[] = $row;
			}				
		}
		return array('tpcmstables'=>$tpcms, 'othertables'=>$other);
	}


	/**
	 * 数据库恢复
	 * @param unknown_type $filename
	 */
	private function import_database($filename) {
		if($filename && fileext($filename)=='sql') {
			$filepath = DATA_PATH.'bakup'.DIRECTORY_SEPARATOR.$this->pdoname.DIRECTORY_SEPARATOR.$filename;
			if(!file_exists($filepath)) showmessage(L('database_sorry')." $filepath ".L('database_not_exist'));
			$sql = file_get_contents($filepath);
			sqlexecute($sql);
			$this->success("$filename 中的数据已经成功导入到数据库！");
		} else {
			$fileid = $this->fileid ? $this->fileid : 1;
			$pre = $filename;
			$filename = $filename.$fileid.'.sql';
			$filepath = DATA_PATH.'bakup'.DIRECTORY_SEPARATOR.$this->pdoname.DIRECTORY_SEPARATOR.$filename;
			if(file_exists($filepath)) {
				$sql = file_get_contents($filepath);
				sqlexecute($sql);
				$fileid++;
				$extra = array (
					'pdoname'  => $this->pdoname,
					'pre'      => $pre,
					'fileid'   => $fileid,
					'dosubmit' => 1
				);
				$this->success("数据文件 $filename 恢复成功！", U('import', $extra));
			} else {
				api('Cache/clear_fields');
				$this->success('数据库恢复成功！', U('import'));
			}
		}
	}

	/**
	 * 数据库导出方法
	 * @param unknown_type $tables 数据表数据组
	 * @param unknown_type $sqlcompat 数据库兼容类型
	 * @param unknown_type $sqlcharset 数据库字符
	 * @param unknown_type $sizelimit 卷大小
	 * @param unknown_type $action 操作
	 * @param unknown_type $fileid 卷标
	 * @param unknown_type $random 随机字段
	 * @param unknown_type $tableid 
	 * @param unknown_type $startfrom 
	 * @param unknown_type $tabletype 备份数据库类型 （非phpcms数据与phpcms数据）
	 */
	private function export_database($tables,$sqlcompat,$sqlcharset,$sizelimit,$action,$fileid,$random,$tableid,$startfrom,$tabletype) {
		$dumpcharset = $sqlcharset ? $sqlcharset : str_replace('-', '', CHARSET);
		$fileid = ($fileid != '') ? $fileid : 1;

		if($fileid==1 && $tables) {
			if(empty($tables) || !is_array($tables)) $this->error('请选择数据表');
			$random = random(20, 'abcdefghigklmzopqrstuvwxyz0123456789');
			setcache('bakup_tables',$tables,'commons');
		} else {
			if(!$tables = getcache('bakup_tables','commons')) $this->error('请选择数据表');
		}

		if($this->version > '4.1'){
			if($sqlcharset) {
				$this->db->query("SET NAMES '".$sqlcharset."';\n\n");
			}
			if($sqlcompat == 'MYSQL40') {
				$this->db->query("SET SQL_MODE='MYSQL40'");
			} elseif($sqlcompat == 'MYSQL41') {
				$this->db->query("SET SQL_MODE=''");
			}
		}
		
		$tabledump = '';

		$tableid = ($tableid!= '') ? $tableid - 1 : 0;
		$startfrom = ($startfrom != '') ? intval($startfrom) : 0;
		for($i = $tableid; $i < count($tables) && strlen($tabledump) < $sizelimit * 1000; $i++) {
			global $startrow;
			$offset = 100;
			if(!$startfrom) {
				$createtable = $this->db->query("SHOW CREATE TABLE `$tables[$i]` ");
				$tabledump .= "DROP TABLE IF EXISTS `$tables[$i]`;\n";
				$tabledump .= $createtable[0]['Create Table'].";\n\n";		
				if($sqlcompat == 'MYSQL41' && $this->version < '4.1') {
					$tabledump = preg_replace("/TYPE\=([a-zA-Z0-9]+)/", "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
				}
				if($this->version > '4.1' && $sqlcharset) {
					$tabledump = preg_replace("/(DEFAULT)*\s*CHARSET=[a-zA-Z0-9]+/", "DEFAULT CHARSET=".$sqlcharset, $tabledump);
				}
				if($tables[$i]==DB_PRE.'session') {
					$tabledump = str_replace("CREATE TABLE `".DB_PRE."session`", "CREATE TABLE IF NOT EXISTS `".DB_PRE."session`", $tabledump);
				}
			}
			$numrows = $offset;
			while(strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset) {
				$_tables = preg_replace('/'.C('DB_PREFIX').'/i','',$tables[$i]);
				
				$numrows = M($_tables)->limit($startfrom, $offset)->count();
				$fields_name = M($_tables)->getDbFields();//获取该表所有字段
				$numfields = count($fields_name);//获取字段总数
				$rows = M($_tables)->limit($startfrom, $offset)->select();
				$r = array();
				foreach ($rows as $k => $row) {
					$tabledump .= "INSERT INTO `$tables[$i]` VALUES(";
					for($j = 0; $j < $numfields; $j++) {
						$tabledump .= $comma."'".mysql_escape_string($row[$fields_name[$j]])."'";
						$comma = ",";
					}
					$tabledump .= ");\n";					
				}
				$startfrom += $offset;	
			}
			$tabledump .= "\n";
			$startrow = $startfrom;
			$startfrom = 0;

		}
		if(trim($tabledump)) {
			helpers('dir');
			$tabledump = "# tpcms bakfile\n# version:TPCMS ".TPCMS_VERSION."\n# time:".date('Y-m-d H:i:s')."\n# type:tpcms\n# tpcms:http://www.tpcms.cn\n# --------------------------------------------------------\n\n\n".$tabledump;
			$tableid = $i;
			$filename = $random.'_'.$tabletype.'_'.date('Ymd').'_'.$fileid.'.sql';
			$altid = $fileid;
			$fileid++;
			$bakfile_path = DATA_PATH.'bakup'.DIRECTORY_SEPARATOR.$this->pdo_name;
			if(!dir_create($bakfile_path)) {
				$this->error('目录创建失败');
			}
			$bakfile = $bakfile_path.DIRECTORY_SEPARATOR.$filename;
			if(!is_writable(DATA_PATH.'bakup')) $this->error('备份目录无写入权限');
			file_put_contents($bakfile, $tabledump);
			@chmod($bakfile, 0777);
			if(!EXECUTION_SQL) $filename = L('bundling').$altid.'#';
			$extra = array(
				'sizelimit'  => $sizelimit,
				'sqlcompat'  => $sqlcompat,
				'sqlcharset' => $sqlcharset,
				'tableid'    => $tableid,
				'fileid'     => $fileid,
				'startfrom'  => $startrow,
				'random'     => $random,
				'dosubmit'   => 1,
				'tabletype'  => $tabletype,
				'allow'      => $allow
			);
			$this->success("备份文件 $filename 写入成功", U('export', $extra));
		} else {
		   $bakfile_path = DATA_PATH.'bakup'.DIRECTORY_SEPARATOR.$this->pdo_name.DIRECTORY_SEPARATOR;
		   file_put_contents($bakfile_path.'index.html','');
		   delcache('bakup_tables','commons');
		   $this->success('备份成功', U('import'));
		}
	}

}
?>